#include "SoundSource.h"
#include "D3D9Engine.h"


CResourceSoundSource::CResourceSoundSource()
{
	this->m_file		= NULL;
	this->m_fileType	= SNDFT_NULL;
	this->m_sourceID	= 0;
}

CResourceSoundSource::~CResourceSoundSource()
{
}

bool CResourceSoundSource::CreateSoundSource(const char *_file, SND_FILETYPE _fileType)
{
	this->m_file		= _file;
	this->m_fileType	= _fileType;

	return true;
}

bool CResourceSoundSource::OnInitResource(ICompHandler *_handler)
{
	CD3D9Engine* ptr_engine = (CD3D9Engine*) _handler;

	if (ptr_engine)
	{
		ptr_engine->GetSoundAPI()->GenerateSources(1, &this->m_sourceID);
		
		this->m_bufferID = ptr_engine->GetResourceFactory()->RegisterSoundBuffer(this->m_file, this->m_fileType);

		this->BufferData(this->m_bufferID);

		return true;
	}

	return false;
}

bool CResourceSoundSource::OnFreeResource(ICompHandler *_handler)
{
	CD3D9Engine* ptr_engine = (CD3D9Engine*) _handler;

	if (ptr_engine)
	{
		ptr_engine->GetResourceFactory()->UnregisterSoundBuffer(this->m_file);

		return (ptr_engine->GetSoundAPI()->ReleaseSources(1, &this->m_sourceID));
	}

	return false;
}

bool CResourceSoundSource::BufferData(ALuint _bufferID)
{
	alSourcei(this->m_sourceID, AL_BUFFER, _bufferID);

	if (alGetError() != AL_NO_ERROR)
	{
		this->m_bufferID = _bufferID;
		return false;
	}

	return true;
}

bool CResourceSoundSource::Play()
{
	alSourcePlay(this->m_sourceID);

	return (alGetError() == AL_NO_ERROR);
}

bool CResourceSoundSource::Pause()
{
	alSourcePause(this->m_sourceID);

	return (alGetError() == AL_NO_ERROR);

}

bool CResourceSoundSource::Stop()
{
	alSourceStop(this->m_sourceID);

	return (alGetError() == AL_NO_ERROR);
}


bool CResourceSoundSource::IsPlaying()
{
	ALint state;
	alGetSourcei(this->m_sourceID, AL_SOURCE_STATE, &state);
	return (state == AL_PLAYING);
}
